#!/usr/bin/env ruby

require 'fileutils'
require 'yaml'
require 'pathname'

unless defined? ROR_SERVICE_ROOT
  ROR_SERVICE_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..'))
  $:.unshift(ROR_SERVICE_ROOT)
end

require 'container/mongrel_controller'
require 'container/utils'

class SiteController

  include FileUtils
  include Utils

  def self.valid_domain?(domain)
    not domain.include?('/') and File.directory?(File.join(ROR_SERVICE_ROOT, 'config', 'sites', domain))
  end

  def initialize(domain)
    raise "Unknown domain #{domain}" unless SiteController.valid_domain?(domain)
    @domain = domain
    @mongrel_controller = MongrelController.for_domain(@domain)
  end

  def start 

    Dir["#{@mongrel_controller.config_dir}/monit.*.config.stopped"].each do |stopped_config_file|
      mv stopped_config_file, stopped_config_file.sub(/\.stopped$/, '')
    end

    hosts = active_mongrels.map { |m| m.host }.sort.uniq
    reload_monits(hosts)

    active_mongrels.each do |mongrel|
      execute("monit -c #{monit_config(mongrel.host)} start #{mongrel.monit_service_name}")
    end
  end

  def stop
    affected_hosts = []
    active_mongrels.each do |mongrel|
      affected_hosts << mongrel.host 
      execute("monit -c #{monit_config(mongrel.host)} stop #{mongrel.monit_service_name}")
      mv mongrel.monit_config_path, "#{mongrel.monit_config_path}.stopped"
    end

    Dir["#{@mongrel_controller.config_dir}/monit.*.config"].each do |active_config_file|

    end

    reload_monits(affected_hosts.sort.uniq)
  end

  def restart
    stop
    start
  end

  def all_mongrels
    MongrelInstance.find_all(@mongrel_controller)
  end

  def active_mongrels
    MongrelInstance.find_active(@mongrel_controller)
  end

  def reload_monits(hosts)
    hosts.each do |host|
      execute("monit -c #{monit_config(host)} reload")
    end
  end

  def monit_config(host)
    "#{File.join(ROR_SERVICE_ROOT, 'config', "monit.#{host}.config")}"
  end

end

if $0 == __FILE__
  action, domain = ARGV

  errors = []
  errors << "action and container root are mandatory parameters" unless action and domain
  errors << "Unknown action: #{action}" unless %w(start stop restart).include? action
  errors << "Unknown domain: #{domain}" unless SiteController.valid_domain?(domain)

  unless errors.empty?
    errors.unshift "Usage: site_controller.rb start|stop|restart <domain>"
    STDERR.puts errors
    exit 1
  end

  SiteController.new(domain).send(action)
end
